package com.jinglu.cloud.security.impl;

import com.alibaba.fastjson.JSON;
import com.jinglu.cloud.security.model.AuthInfo;
import com.jinglu.cloud.security.utils.RedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Author lvzhenzhao
 * @Datetime 2021/03/02-下午3:22
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RedisRepository redisRepository;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        if (!StringUtils.isEmpty(userName)) {
            StringBuilder keyBuilder = new StringBuilder("user-details:");
            keyBuilder.append(userName);
            String userDetailKeyValue = redisRepository.get(keyBuilder.toString());
            return !StringUtils.isEmpty(userDetailKeyValue) ? JSON.parseObject(userDetailKeyValue, AuthInfo.class) : null;
        }
        return null;
    }
}
